/*
 * Created by JFormDesigner on Mon Jul 01 15:14:11 CST 2024
 */

package com.hongyan.view.admin;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.table.*;

import com.hongyan.base.BaseContentJpanel;
import com.hongyan.bean.Document;
import com.hongyan.config.MainFrameConfig;
import com.hongyan.dao.DocumentDao;
import com.hongyan.page.AbstractStatusBar;
import com.hongyan.page.PageInfo;
import com.hongyan.widget.ButtonDocumentEditor;
import com.hongyan.widget.ButtonEditor;
import com.hongyan.widget.ButtonRenderer;
import com.hongyan.widget.TableButtonClick;
import org.apache.commons.io.FileUtils;

/**
 * @author admin
 */
public class SwingAdminDocumentPanel extends BaseContentJpanel {

    private static Object[] head = new Object[]{"编号", "文件名", "上传日期", "操作"};
    private DefaultTableModel tableModel;

    public SwingAdminDocumentPanel() {
        super();
        initData();
    }

    @Override
    public void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents  @formatter:off
        textField1 = new JTextField();
        label1 = new JLabel();
        button1 = new JButton();
        button2 = new JButton();
        button3 = new JButton();
        scrollPane1 = new JScrollPane();
        table1 = new JTable();

        //======== this ========
        setLayout(null);
        add(textField1);
        textField1.setBounds(65, 25, 105, textField1.getPreferredSize().height);

        //---- label1 ----
        label1.setText("\u6587\u4ef6\u540d");
        add(label1);
        label1.setBounds(new Rectangle(new Point(20, 30), label1.getPreferredSize()));

        //---- button1 ----
        button1.setText("\u641c\u7d22");
        button1.setBackground(new Color(0x3399ff));
        add(button1);
        button1.setBounds(new Rectangle(new Point(395, 25), button1.getPreferredSize()));

        //---- button2 ----
        button2.setText("\u91cd\u7f6e");
        add(button2);
        button2.setBounds(new Rectangle(new Point(490, 25), button2.getPreferredSize()));

        //---- button3 ----
        button3.setText("\u589e\u52a0");
        add(button3);
        button3.setBounds(new Rectangle(new Point(10, 70), button3.getPreferredSize()));

        //======== scrollPane1 ========
        {
            scrollPane1.setViewportView(table1);
        }
        add(scrollPane1);
        scrollPane1.setBounds(0, 105, 700, 395);

        {
            // compute preferred size
            Dimension preferredSize = new Dimension();
            for(int i = 0; i < getComponentCount(); i++) {
                Rectangle bounds = getComponent(i).getBounds();
                preferredSize.width = Math.max(bounds.x + bounds.width, preferredSize.width);
                preferredSize.height = Math.max(bounds.y + bounds.height, preferredSize.height);
            }
            Insets insets = getInsets();
            preferredSize.width += insets.right;
            preferredSize.height += insets.bottom;
            setMinimumSize(preferredSize);
            setPreferredSize(preferredSize);
        }
        // JFormDesigner - End of component initialization  //GEN-END:initComponents  @formatter:on
    }

    @Override
    public void initData() {

        JTableHeader header = table1.getTableHeader();
        header.setPreferredSize(new Dimension(header.getWidth(), 30));
        header.setFont(new Font("华文楷体", Font.PLAIN, 18));
        setTableColumnCenter(table1);
        table1.setBorder(new LineBorder(new Color(0, 0, 0)));
        table1.setAlignmentX(CENTER_ALIGNMENT);
        table1.setShowHorizontalLines(true);
        table1.setShowVerticalLines(true);
        table1.setIntercellSpacing(new Dimension(1, 1));
        tableModel = new DefaultTableModel(null, head) {
            @Override
            public boolean isCellEditable(int row, int column) {
                if (column == 3) {
                    return true;
                } else {
                    return false;
                }

            }
        };
        table1.setModel(tableModel);
        statusBar = new AbstractStatusBar() {
            @Override
            public String getTableName() {
                // TODO Auto-generated method stub
                // 组装全部查询语句

                return "document";
            }

            @Override
            public void fillToTable(PageInfo pageInfo) {

                String cursql = pageInfo.getCurQuerySQL();
                Object[][] documentListBySql = DocumentDao.getDocumentListBySql(cursql);
                tableModel.getDataVector().clear();
                for (Object[] objects : documentListBySql) {
                    tableModel.addRow(objects);
                }
            }
        };
        add(statusBar);
        statusBar.setBounds(0, 500, 700, 95);
        loaddata();

        table1.getColumn("操作").setCellRenderer(new ButtonRenderer("操作"));
        table1.getColumn("操作").setCellEditor(new ButtonDocumentEditor("操作", table1, new TableButtonClick() {
            @Override
            public void onClick(int type, String id,Object data) {
                if (type == 1) {
                    JOptionPane.showMessageDialog(MainFrameConfig.getSwingMainFrame(), id + "修改成功");
                } else {
                    int i = DocumentDao.deleteDocumentBySql(id);
                    if (i > 0) {
                        JOptionPane.showMessageDialog(MainFrameConfig.getSwingMainFrame(), "删除成功");
                        loaddata();
                    } else {
                        JOptionPane.showMessageDialog(MainFrameConfig.getSwingMainFrame(), "删除失败");
                    }
                }
            }


        }));

    }

    @Override
    public void initListen() {
        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String text = textField1.getText();
                if (text.isEmpty()) {
                    showToast("请输入查询条件");
                } else {
                    System.out.println("text = " + text);
                    loaddata(text);
                }
            }
        });
        button2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                textField1.setText("");
                loaddata();
            }
        });
        button3.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                int returnValue = fileChooser.showOpenDialog(null);
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = fileChooser.getSelectedFile();
                    String name = selectedFile.getName();
                    int userOption = JOptionPane.showConfirmDialog(null, "确定上传" + name + "文件？", "提示", JOptionPane.OK_OPTION, JOptionPane.QUESTION_MESSAGE);    //确认对话框
//如果用户选择的是OK
                    if (userOption == JOptionPane.OK_OPTION) {

                        try {
                            Document document = new Document();
                            document.setD_id(MainFrameConfig.getSnowflakeUtils().getId());
                            document.setD_name(name);
                            document.setUpload_time(new java.sql.Timestamp(System.currentTimeMillis()));
                            document.setDocument_upload(FileUtils.readFileToByteArray(selectedFile));
                            if (DocumentDao.insertDocumentBySql(document) > 0) {
                                JOptionPane.showMessageDialog(null, "上传成功");
                                loaddata();
                            } else {
                                JOptionPane.showMessageDialog(null, "上传失败");
                            }
                        } catch (IOException ex) {
                            throw new RuntimeException(ex);
                        }
                    }
                }
            }
        });
    }

    private void loaddata(String text) {
        Object[][] documentByName = DocumentDao.findDocumentByName(text);
        tableModel.getDataVector().clear();
        tableModel.setNumRows(0);
        for (Object[] objects : documentByName) {
            tableModel.addRow(objects);
        }
    }

    public void setTableColumnCenter(JTable table) {
        DefaultTableCellRenderer r = new DefaultTableCellRenderer();
        r.setHorizontalAlignment(JLabel.CENTER);
        table.setDefaultRenderer(Object.class, r);
    }


    //查询方法
    public void loaddata() {
        statusBar.loadData();
    }


    private AbstractStatusBar statusBar;

    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables  @formatter:off
    private JTextField textField1;
    private JLabel label1;
    private JButton button1;
    private JButton button2;
    private JButton button3;
    private JScrollPane scrollPane1;
    private JTable table1;
    // JFormDesigner - End of variables declaration  //GEN-END:variables  @formatter:on
}

